const GUIDANCE_KEY = 'GUIDANCE_OBJ';
const PLAYVOICE_KEY = 'PLAYVOICE_BOOL';
const SUBJECT_LOOKED_TIME_KEY = 'SUBJECT_LOOKED_TIME'
const GUIDANCE_Map = {
  ynxl: 1, // 右脑训练
  dcxx: 1 // 单词学习
}

const store = {
  initialData() {
    this.initPlayVoice();
    this.initGuidance();
  },
  /**
   * 初始化引导数据
   */
  initGuidance() {
    this.setGuidance(GUIDANCE_Map);
  },
  getGuidance( fn ) {
    this.getStore( GUIDANCE_KEY, data => {
      fn && fn( data )
    } )
  },
  addCountOfSubjectLooked(id, time) {
    try {
      var value = wx.getStorageSync(SUBJECT_LOOKED_TIME_KEY)
      if (!value) {
        value = {};
      }
      if (value[id]) {
        value[id].no = value[id].no + 1;
        value[id].time = time
        if (value[id].time != time) {
          value[id].no = 1;
        }
        
      } else {
        value[id] = {
          no: 1,
          time: time
        };
      }
      this.setStore(SUBJECT_LOOKED_TIME_KEY, value, () => {
        console.log('科目查看次数递增成功.')
      })
    } catch (e) {
      console.log(e);
    }
  },
  getAccountOfSubjectsLooked(fn) {
    return wx.getStorageSync(SUBJECT_LOOKED_TIME_KEY) || null
  },
  setGuidance( data ) {
    this.setStore( GUIDANCE_KEY, data );
  },
  getGuidTimeByKey( key, fn ) {
    this.getGuidance( data => {
      if ( !data[ key ] ) {
        console.error( 'the key is error: ' + key );
        return;
      }
      fn && fn( data[ key ] ); 
      // 每次访问自增 1
      data[ key ] = data[ key ] + 1
      this.setGuidance( data );
    } )
  },
  initPlayVoice() {
    this.setPlayVoice( 'open' );
  },
  setPlayVoice( val ) {
    this.setStore( PLAYVOICE_KEY, val);
  },
  getPlayVoice( fn ) {
    this.getStore( PLAYVOICE_KEY, data => {
      fn && fn( data );
    })
  },
  setStore(key, val, fn) {
    wx.setStorage({
      key: key,
      data: val,
      success() {
        fn && fn()
      }
    })
  },
  getStore( key, fn ) {
    wx.getStorage({
      key: key,
      success( res ) {
        fn && fn( res.data ); 
      }
    })
  }
}

module.exports = store;